package me.wangqu.weiyouqu.web.rest;

import com.codahale.metrics.annotation.Timed;
import me.wangqu.weiyouqu.domain.SysMessage;
import me.wangqu.weiyouqu.repository.SysMessageRepository;
import me.wangqu.weiyouqu.security.AuthoritiesConstants;
import me.wangqu.weiyouqu.web.rest.util.HeaderUtil;
import me.wangqu.weiyouqu.web.rest.util.PaginationUtil;
import me.wangqu.weiyouqu.web.rest.dto.SysMessageDTO;
import me.wangqu.weiyouqu.web.rest.mapper.SysMessageMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * REST controller for managing SysMessage.
 */
@RestController
@RequestMapping("/api")
public class SysMessageResource {

    private final Logger log = LoggerFactory.getLogger(SysMessageResource.class);

    @Inject
    private SysMessageRepository sysMessageRepository;

    @Inject
    private SysMessageMapper sysMessageMapper;

    @RequestMapping(value = "/sys-messages/sent",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Transactional(readOnly = true)
    public ResponseEntity<List<SysMessageDTO>> getSysMessagesSent(Pageable pageable)
            throws URISyntaxException {
        log.debug("REST request to get a page of SysMessages");
        if (pageable.getSort() == null) {
            pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(Sort.Direction.DESC, "time"));
        }
        // 1 - 编辑中, 2 - 待发送, 3 - 已发送
        Page<SysMessage> page = sysMessageRepository.findByStatus(3, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/sys-messages");
        return new ResponseEntity<>(sysMessageMapper.sysMessagesToSysMessageDTOs(page.getContent()), headers, HttpStatus.OK);
    }

    /**
     * POST  /sys-messages : Create a new sysMessage.
     *
     * @param sysMessageDTO the sysMessageDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new sysMessageDTO, or with status 400 (Bad Request) if the sysMessage has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/sys-messages",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<SysMessageDTO> createSysMessage(@Valid @RequestBody SysMessageDTO sysMessageDTO) throws URISyntaxException {
        log.debug("REST request to save SysMessage : {}", sysMessageDTO);
        if (sysMessageDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("sysMessage", "idexists", "A new sysMessage cannot already have an ID")).body(null);
        }
        SysMessage sysMessage = sysMessageMapper.sysMessageDTOToSysMessage(sysMessageDTO);
        sysMessage = sysMessageRepository.save(sysMessage);
        SysMessageDTO result = sysMessageMapper.sysMessageToSysMessageDTO(sysMessage);
        return ResponseEntity.created(new URI("/api/sys-messages/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("sysMessage", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /sys-messages : Updates an existing sysMessage.
     *
     * @param sysMessageDTO the sysMessageDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated sysMessageDTO,
     * or with status 400 (Bad Request) if the sysMessageDTO is not valid,
     * or with status 500 (Internal Server Error) if the sysMessageDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/sys-messages",
        method = RequestMethod.PUT,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<SysMessageDTO> updateSysMessage(@Valid @RequestBody SysMessageDTO sysMessageDTO) throws URISyntaxException {
        log.debug("REST request to update SysMessage : {}", sysMessageDTO);
        if (sysMessageDTO.getId() == null) {
            return createSysMessage(sysMessageDTO);
        }
        SysMessage sysMessage = sysMessageMapper.sysMessageDTOToSysMessage(sysMessageDTO);
        sysMessage = sysMessageRepository.save(sysMessage);
        SysMessageDTO result = sysMessageMapper.sysMessageToSysMessageDTO(sysMessage);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("sysMessage", sysMessageDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /sys-messages : get all the sysMessages.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of sysMessages in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @RequestMapping(value = "/sys-messages",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<List<SysMessageDTO>> getAllSysMessages(Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of SysMessages");
        Page<SysMessage> page = sysMessageRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/sys-messages");
        return new ResponseEntity<>(sysMessageMapper.sysMessagesToSysMessageDTOs(page.getContent()), headers, HttpStatus.OK);
    }

    /**
     * GET  /sys-messages/:id : get the "id" sysMessage.
     *
     * @param id the id of the sysMessageDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the sysMessageDTO, or with status 404 (Not Found)
     */
    @RequestMapping(value = "/sys-messages/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<SysMessageDTO> getSysMessage(@PathVariable Long id) {
        log.debug("REST request to get SysMessage : {}", id);
        SysMessage sysMessage = sysMessageRepository.findOne(id);
        SysMessageDTO sysMessageDTO = sysMessageMapper.sysMessageToSysMessageDTO(sysMessage);
        return Optional.ofNullable(sysMessageDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /sys-messages/:id : delete the "id" sysMessage.
     *
     * @param id the id of the sysMessageDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @RequestMapping(value = "/sys-messages/{id}",
        method = RequestMethod.DELETE,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<Void> deleteSysMessage(@PathVariable Long id) {
        log.debug("REST request to delete SysMessage : {}", id);
        sysMessageRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("sysMessage", id.toString())).build();
    }

}
